using AutoMapper;
using B.S.RbacData.Infrastructure;
using MediatR;
using SupplierCustomerManagement.Domain.Entities;
using B.S.RbacData.ErrorCode;
using SupplierCustomerManagement.Write.API.Applications.Commands.bankaccounts;

namespace SupplierCustomerManagement.Write.API.Applications.CommandHandlters.bankaccounts
{
    /// <summary>
    /// 更新银行账户命令处理器
    /// </summary>
    public class UpdateBankAccountCommandHandler : IRequestHandler<UpdateBankAccountCommand, ApiResult<bool>>
    {
        private readonly IBaseRepository<BankAccount> _bankAccountRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<UpdateBankAccountCommandHandler> _logger;

        public UpdateBankAccountCommandHandler(
            IBaseRepository<BankAccount> bankAccountRepository,
            IMapper mapper,
            ILogger<UpdateBankAccountCommandHandler> logger)
        {
            _bankAccountRepository = bankAccountRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理更新银行账户命令
        /// </summary>
        /// <param name="request">更新银行账户命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>更新结果</returns>
        public async Task<ApiResult<bool>> Handle(UpdateBankAccountCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始更新银行账户，银行账户ID: {BankAccountId}, 账户号码: {AccountNumber}", 
                    request.Id, request.AccountNumber);

                // 查找要更新的银行账户
                var existingBankAccount =  _bankAccountRepository.GetAll().FirstOrDefault(x=>x.Id== request.Id);

                if (existingBankAccount == null || existingBankAccount.IsDeleted)
                {
                    _logger.LogWarning("未找到指定的银行账户，银行账户ID: {BankAccountId}", request.Id);
                    
                    return new ApiResult<bool>
                    {
                        code = ResultEnumCode.fails,
                        message = "未找到指定的银行账户",
                        data = false
                    };
                }

                // 检查账户号码是否被其他账户使用
                var duplicateAccount =  _bankAccountRepository.GetAll().FirstOrDefault(
                    ba => ba.AccountNumber == request.AccountNumber && ba.Id != request.Id && !ba.IsDeleted);

                if (duplicateAccount != null)
                {
                    _logger.LogWarning("银行账户号码已被其他账户使用: {AccountNumber}", request.AccountNumber);
                    
                    return new ApiResult<bool>
                    {
                        code = ResultEnumCode.fails,
                        message = "该银行账户号码已被其他账户使用",
                        data = false
                    };
                }

                // 更新银行账户信息
                existingBankAccount.RelatedEntityId = request.RelatedEntityId;
                existingBankAccount.RelatedEntityType = request.RelatedEntityType;
                existingBankAccount.BankName = request.BankName;
                existingBankAccount.AccountName = request.AccountName;
                existingBankAccount.OpeningBank = request.OpeningBank;
                existingBankAccount.AccountNumber = request.AccountNumber;
                existingBankAccount.AccountType = request.AccountType;
                existingBankAccount.AccountProperty = request.AccountProperty;
                existingBankAccount.AccountRelationshipType = request.AccountRelationshipType;
                existingBankAccount.MobileNumber = request.MobileNumber;
                existingBankAccount.IdNumber = request.IdNumber;
                existingBankAccount.Remarks = request.Remarks;
                existingBankAccount.UpdatedTime = DateTime.Now;
                existingBankAccount.UpdatedBy =1; // 后续可以从当前用户上下文获取

                // 保存更新
                await _bankAccountRepository.UpdateAsync(existingBankAccount);

                _logger.LogInformation("成功更新银行账户，银行账户ID: {BankAccountId}, 账户号码: {AccountNumber}", 
                    request.Id, request.AccountNumber);

                return new ApiResult<bool>
                {
                    code = ResultEnumCode.Ok,
                    message = "更新银行账户成功",
                    data = true
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新银行账户时发生异常，银行账户ID: {BankAccountId}", request.Id);
                
                return new ApiResult<bool>
                {
                    code = ResultEnumCode.fails,
                    message = $"更新银行账户时发生异常: {ex.Message}",
                    data = false
                };
            }
        }
    }
}